package geoway.bmf.keycloak.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yrt
 * @description okHttp工具类
 * @date 2022/12/3 17:11
 */
@Slf4j
public class OkHttpUtil {
    /**
     * 工具类，构造方法私有化
     */
    private OkHttpUtil() {
        super();
    }

    /**
     * get
     *
     * @param url       请求的url
     * @param parameter 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return 返回内容
     */
    public static String get(String url, Map<String, String> parameter) {
        return get(url, parameter, null);
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param headMap 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return 返回内容
     */
    public static String getForHeader(String url, Map<String, String> headMap) {
        return get(url, null, headMap);
    }

    /**
     * get请求
     *
     * @param url       请求url
     * @param parameter 请求参数
     * @param headMap   请求头
     * @return 返回内容
     */
    public static String get(String url, Map<String, String> parameter, Map<String, String> headMap) {
        url = appendUrl(url, parameter);
        Request.Builder builder = getRequestBuilder(headMap);
        Request request = builder.url(url).build();
        return getResponse(request);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return 返回内容
     */
    public static String post(String url, Map<String, Object> params) {
        return post(url, params, null);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return 返回内容
     */
    public static String post(String url, Map<String, Object> params, Map<String, String> headMap) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && !params.keySet().isEmpty()) {
            for (String key : params.keySet()) {
                if (params.get(key) == null) {
                    continue;
                }
                builder.add(key, params.get(key).toString());
            }
        }

        Request.Builder requestBuilder = getRequestBuilder(headMap);
        Request request = requestBuilder
                .url(url)
                .post(builder.build())
                .build();

        return getResponse(request);
    }

    /**
     * Post请求发送JSON数据....{"name":"tom","pwd":"123456"}
     *
     * @param url
     * @param jsonParams
     * @return 返回内容
     */
    public static String postJson(String url, String jsonParams) {
        return postString(url, jsonParams, "json");
    }

    /**
     * Post请求发送xml数据....
     *
     * @param url
     * @param xml
     * @return 返回内容
     */
    public static String postXml(String url, String xml) {
        return postString(url, xml, "xml");
    }

    /**
     * 下载文件
     *
     * @param downloadUrl 文件Url
     * @param filePath    文件下载地址
     * @throws Exception
     */
    public void downloadFile(final String downloadUrl, String filePath) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(downloadUrl).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("文件下载错误:" + response);
        }
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(response.body().bytes());
        fos.close();
    }

    /**
     * 拼接url
     *
     * @param url
     * @param map
     * @return
     */
    private static String appendUrl(String url, Map<String, String> map) {
        StringBuilder sb = new StringBuilder(url);
        if (map != null && !map.keySet().isEmpty()) {
            boolean firstFlag = true;
            for (Map.Entry entry : map.entrySet()) {
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取Builder
     *
     * @param map
     * @return
     */
    private static Request.Builder getRequestBuilder(Map<String, String> map) {
        Request.Builder builder = new Request.Builder();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                builder.addHeader(mapKey, mapValue);
            }
        }
        return builder;
    }

    /**
     * post字符串
     *
     * @param url
     * @param data
     * @param type
     * @return
     */
    private static String postString(String url, String data, String type) {
        MediaType mediaType = MediaType.Companion.parse("application/" + type + "; charset=utf-8");
        RequestBody requestBody = RequestBody.Companion.create(data, mediaType);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return getResponse(request);
    }

    /**
     * 获取返回结果
     *
     * @param request
     * @return
     */
    private static String getResponse(Request request) {
        try (Response response = getClient().newCall(request).execute()) {
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okHttp3 " + request.method() + " 网络请求错误,请求地址:" + request.url(), e);
        }
        return null;
    }

    /**
     * 获取请求客户端
     *
     * @return
     */
    private static OkHttpClient getClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }
}
